/**
 * Created by chengke on 2018/2/28.
 */

let iconv = require('iconv-lite');
let FutuHttpClient = require('@futu/httpclient');
let FutuHttpRequest = FutuHttpClient.FutuHttpRequest;
let Keyword = require('../models/Keyword');
let Adgroup = require('../models/Adgroup');
let KeywordBinding = require('../models/KeywordBinding');

module.exports = KeywordService;

const BASE_API_URL = 'https://api.baidu.com/json/sms/service/KeywordService/';
const API_GET_WORD = 'getWord';
const API_ADD_WORD = 'addWord';
const API_UPDATE_WORD = 'updateWord';
const API_DELETE_WORD = 'deleteWord';

const KEYWORD_ATTRS = [
    'campaignId',
    'adgroupId',
    'keywordId',
    'pcDestinationUrl',
    'mobileDestinationUrl',
    'phraseType',
    'keyword',
    'price',
    'matchType',
    'pause',
    'status',
    'wmatchprefer',
    'pcQuality',
    'pcScale',
    'mobileQuality',
    'mobileScale'
];

/**
 * KeywordService
 *
 * @constructor
 * @param {String} username 用户名
 * @param {String} password 密码
 * @param {String} token API 令牌
 * @param {Object} options 扩展参数
 */
function KeywordService(username, password, token, options = {}) {
    this.username = username;
    this.password = password;
    this.token = token;
    this.options = options;
    this.commonHeader = {
        'username': this.username,
        'password': this.password,
        'token': this.token
    };
}

KeywordService.prototype.getWord = async function () {
    let adgroups = await Adgroup.findAll({attributes: ['adgroup_id']});
    let adgroupIds = adgroups.map(function (adgroup) {
        return adgroup.dataValues.adgroup_id;
    });
    let words = [];
    if (adgroupIds.length > 50) {
        let offset = 0;
        let times = Math.ceil(adgroupIds.length / 50);
        for (let i = 0; i < times; i++) {
            let unitIds = adgroupIds.slice(offset, offset + 49);
            console.log(unitIds);
            let result = await this._requestSemAPI(BASE_API_URL + API_GET_WORD, {
                'ids': unitIds,
                'idType': 5,
                'wordFields': KEYWORD_ATTRS
            });
            console.log(JSON.stringify(result, null, 2));
            if (result.header && result.header.status === 0) {
                words = words.concat(result.body.data);
            }
        }
    } else {
        let result = await this._requestSemAPI(BASE_API_URL + API_GET_WORD, {
            'ids': adgroupIds,
            'idType': 5,
            'wordFields': KEYWORD_ATTRS
        });
        console.log(JSON.stringify(result, null, 2));
        if (result.header && result.header.status === 0) {
            words = words.concat(result.body.data);
        }
    }
    return words;
};

KeywordService.prototype._requestSemAPI = async function (url, body) {
    let client = await FutuHttpClient.getInstanceByEndpoint();
    let request = new FutuHttpRequest(url, {}, {});
    request.setIsJson(true);
    request.setData({
        'header': this.commonHeader,
        'body': body
    });
    let response = await client.request('post', request);
    if (response.httpStatusCode !== 200) {
        throw new Error('request ' + url + 'failed: ' + response.message);
    }
    return JSON.parse(response.data || '{}');
};

KeywordService.prototype.syncWord = async function () {
    let words = await this.getWord();
    console.log(words.length);
    return words.map(async function (item) {
        item.pcScale = JSON.stringify(item.pcScale);
        item.mobileScale = JSON.stringify(item.mobileScale);
        let word = await Keyword.findOne({
            where: {keyword_id: item.keywordId}
        });
        let result;
        if (word) {
            result = word.update(item);
        } else {
            result = await Keyword.create(item);
        }
        console.log(result);
    });

};

KeywordService.prototype.getOperationRecord = async function (startDate, endDate) {
    let result = await this._requestSemAPI(
        'https://api.baidu.com/json/sms/service/ToolkitService/getOperationRecord',
        {
            'startDate' : startDate,
            'endDate' : endDate,
            'optLevel': 5,
        });
    console.log(JSON.stringify(result, null, 2));
    if (result.header && result.header.status === 0) {
        return result.body.data[0].reportId;
    } else {
        return '';
    }
};

KeywordService.prototype.bindKeyword = async function () {
    let keywords = await Keyword.findAll();
    return await keywords.map(async function (keyword) {
        let channelId = Math.floor(Math.random() * 2) ? 169 : 202;
        let keywordId = keyword.dataValues.keywordId + '';
        let subchannelId = keywordId.slice(0, 5);
        return await KeywordBinding.create({
            keywordId: keywordId,
            channelId: channelId,
            subchannelId: subchannelId
        });
    });
};

KeywordService.timeout = function (ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
};
